<template>
    <div>
        <!-- 已登录 -->
        <div class="app-card" v-if="store.token">
            <div class="app-card-body">
                <div class="user-info-wrap">
                    <img
                            class="user-info-img"
                            :src="(store.userInfo && store.userInfo.headImg) ? store.userInfo.headImg : website.logo"
                            alt=""
                    >
                    <div class="user-info-name">
                        {{
                        (store.userInfo && store.userInfo.nickname) ? store.userInfo.nickname : '未设置'
                        }}
                    </div>
                    <div class="user-info-tel">
                        {{
                        (store.userInfo && store.userInfo.tel) ? store.userInfo.tel : '未绑定'
                        }}
                    </div>
                    <!--<a-tooltip>
                        <template #title>管理书签</template>
                        <a-button shape="circle" class="user-info-setting" @click="pageHref('/manage')">
                            <template #icon>
                                <icon-font type="icon-website"/>
                            </template>
                        </a-button>
                    </a-tooltip>-->
                </div>
                <a-divider/>
                <div class="setting-list">
                    <div class="setting-item" @click="pageHref('/user')">
                        <span>个人中心</span>
                        <img src="/src/assets/imgs/icon-right.svg" alt=""/>
                    </div>
                    <!--<div class="setting-item" @click="pageHref('/manage')">
                        <span>管理引擎/书签</span>
                        <img src="/src/assets/imgs/icon-right.svg" alt=""/>
                    </div>-->
                    <div class="setting-item" @click="showUserDrawer('nickname', '修改昵称')">
                        <span>修改昵称</span>
                        <img src="/src/assets/imgs/icon-right.svg" alt=""/>
                    </div>
                    <div class="setting-item" @click="showUserDrawer('headImg', '修改头像')">
                        <span>修改头像</span>
                        <img src="/src/assets/imgs/icon-right.svg" alt=""/>
                    </div>
                    <div class="setting-item" @click="showUserDrawer('password', '修改密码')">
                        <span>修改密码</span>
                        <img src="/src/assets/imgs/icon-right.svg" alt=""/>
                    </div>
                    <div class="setting-item" @click="loginOut">
                        <span>登出</span>
                        <img src="/src/assets/imgs/icon-right.svg" alt=""/>
                    </div>
                </div>
            </div>
        </div>
        <!-- 未登录 -->
        <div v-else>
            <div class="app-card" v-if="login.state">
                <div class="app-card-header">登录面板</div>
                <div class="app-card-body">
                    <a-form layout="vertical">
                        <a-form-item label="账号">
                            <a-input v-model:value="login.form.account" placeholder="请输入账号"/>
                        </a-form-item>
                        <a-form-item label="密码">
                            <a-input-password v-model:value="login.form.password" placeholder="请输入密码" @pressEnter="loginOk"/>
                        </a-form-item>
                        <a-form-item class="cf">
                            <a class="fl" @click="showRegisterModal">没有账号?</a>
                            <a class="fr" @click="showWxLoginModal">微信快速登录</a>
                        </a-form-item>
                        <a-form-item>
                            <a-button type="primary" block @click="loginOk">登录</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </div>
            <div class="app-card" v-if="register.state">
                <div class="app-card-header">注册面板</div>
                <div class="app-card-body">
                    <a-form layout="vertical">
                        <a-form-item label="账号">
                            <a-input v-model:value="register.form.account" placeholder="请输入账号"/>
                        </a-form-item>
                        <a-form-item label="密码">
                            <a-input-password v-model:value="register.form.password" placeholder="请输入密码"/>
                        </a-form-item>
                        <a-form-item label="重复密码">
                            <a-input-password v-model:value="register.form.passwords" placeholder="再次输入密码"/>
                        </a-form-item>
                        <a-form-item class="cf">
                            <a class="fl" @click="showLoginModal">有账号,去登录</a>
                            <a class="fr" @click="showWxLoginModal">微信快速登录</a>
                        </a-form-item>
                        <a-form-item>
                            <a-button type="primary" block @click="registerOk">注册</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </div>
            <div class="app-card" v-if="wx.state">
                <div class="app-card-header">
                    微信登录
                    <a-button class="header-setting" size="small" @click="gotoLoginModal">返回登录</a-button>
                </div>
                <div class="app-card-body wx-wrap">
                    <img class="wx-img" :src="wx.url" alt=""/>
                    <div class="text-center padding-top" v-if="wx.tag">
                        <a-tag>{{wx.tag}}</a-tag>
                    </div>
                </div>
            </div>
        </div>
        <!-- 打开方式设置 -->
        <div class="app-card">
            <div class="app-card-header">打开方式</div>
            <div class="app-card-body">
                <a-list size="small">
                    <a-list-item v-if="config.openType.search">
                        <span>搜索</span>
                        <template #actions>
                            <a-radio-group size="small"
                                           v-model:value="config.openType.search.value"
                                           @change="searchChange">
                                <a-radio-button
                                        v-for="item in config.openType.search.list"
                                        :value="item.value">
                                    {{item.label}}
                                </a-radio-button>
                            </a-radio-group>
                        </template>
                    </a-list-item>
                    <a-list-item v-if="config.openType.quick">
                        <span>图标</span>
                        <template #actions>
                            <a-radio-group size="small"
                                           v-model:value="config.openType.quick.value"
                                           @change="quickChange">
                                <a-radio-button
                                        v-for="item in config.openType.quick.list"
                                        :value="item.value">
                                    {{item.label}}
                                </a-radio-button>
                            </a-radio-group>
                        </template>
                    </a-list-item>
                    <a-list-item v-if="config.openType.bookmark">
                        <span>书签</span>
                        <template #actions>
                            <a-radio-group size="small"
                                           v-model:value="config.openType.bookmark.value"
                                           @change="bookmarkChange">
                                <a-radio-button
                                        v-for="item in config.openType.bookmark.list"
                                        :value="item.value">
                                    {{item.label}}
                                </a-radio-button>
                            </a-radio-group>
                        </template>
                    </a-list-item>
                </a-list>
            </div>
        </div>
        <!-- 快捷键 -->
        <div class="app-card quick-key-card" v-if="config.quickKey">
            <div class="app-card-header">
                <span>快捷键</span>
                <a-tooltip>
                    <template #title>快捷键操作</template>
                    <QuestionCircleOutlined class="header-setting"/>
                </a-tooltip>
            </div>
            <div class="app-card-body">
                <a-list size="small">
                    <a-list-item v-for="(item, index) in config.quickKey" :key="index">
                        <span class="quick-key-value">{{item.value}}</span>
                        <template #actions>{{item.label}}</template>
                    </a-list-item>
                </a-list>
            </div>
        </div>
        <!-- 常规设置 -->
        <div class="app-card">
            <div class="app-card-header">常规</div>
            <div class="app-card-body">
                <a-list size="small">
                    <!--<a-list-item>
                        <span>消息角标</span>
                        <template #actions>
                            <a-switch size="small"/>
                        </template>
                    </a-list-item>-->
                    <a-list-item>
                        <span>清理缓存</span>
                        <template #actions>
                            <a-button size="small" @click="clearLocalStorage">清理</a-button>
                        </template>
                    </a-list-item>
                </a-list>
            </div>
        </div>
        <!-- 用户信息设置 -->
        <a-drawer
                :title="user.title"
                width="320"
                :closable="false"
                :visible="user.state"
                @close="closeUserDrawer"
        >
            <!--<a-button type="primary" @click="showChildrenDrawer">This is two-level drawer</a-button>-->
            <a-form layout="vertical" v-if="user.type == 'nickname'">
                <a-form-item label="新昵称">
                    <a-input v-model:value="user.nickname" placeholder="输入新昵称"/>
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" @click.prevent="nicknameSubmit">提交</a-button>
                </a-form-item>
            </a-form>
            <div class="text-center" v-if="user.type == 'headImg'">
                <img class="head-img"
                     :src="(store.userInfo && store.userInfo.headImg) ? store.userInfo.headImg : website.logo"
                     alt=""/>
                <a-divider/>
                <a-upload
                        name="file"
                        v-model:file-list="user.headImgList"
                        :data="user.uploadData"
                        :action="getHeadImgUrl"
                        :before-upload="beforeUpload"
                        :show-upload-list="false"
                        @change="handleChange"
                >
                    <a-button>
                        <upload-outlined></upload-outlined>
                        上传
                    </a-button>
                </a-upload>
            </div>
            <a-form layout="vertical" v-if="user.type == 'password'">
                <a-form-item label="旧密码">
                    <a-input type="password" v-model:value="user.password.old" placeholder="输入旧密码"/>
                </a-form-item>
                <a-form-item label="新密码">
                    <a-input type="password" v-model:value="user.password.pass" placeholder="输入新密码"/>
                </a-form-item>
                <a-form-item label="确认新密码">
                    <a-input type="password" v-model:value="user.password.rept" placeholder="再次确认"/>
                </a-form-item>
                <a-form-item>
                    <a-button type="primary" @click.prevent="passwordSubmit">提交</a-button>
                </a-form-item>
            </a-form>
        </a-drawer>
    </div>
</template>

<script>
    import {wsUrl, appUrl} from "/src/config/env";
    import {createVNode} from "vue";
    import {useStore} from "vuex";
    import website from "/src/config/website";
    import {isChrome, getConfig, goUrl, getRandomNum, clearStorage, sendMsgToExtension} from "/src/util";
    import {closeSocket, createSocket, endPing, sendPing, sendWSPush} from "/src/util/socket";

    import {headImgUrl, updateName, updatePassword} from "/src/request/api/user";
    import {getWxAppletsDoor} from "/src/request/api/server";

    // iconfont
    import {
        createFromIconfontCN,
        ExclamationCircleOutlined,
        UploadOutlined,
        QuestionCircleOutlined
    } from '@ant-design/icons-vue';

    const IconFont = createFromIconfontCN({scriptUrl: website.iconfontUrl});
    let config = getConfig();

    export default {
        name: "Base",
        // 组件
        components: {
            IconFont,
            UploadOutlined,
            QuestionCircleOutlined,
        },
        // 数据
        data() {
            return {
                website: website,

                // vuex 状态
                store: useStore().state,
                //userInfo: null,

                config: {},

                // 用户信息
                user: {
                    state: false,
                    type: '',           // nickname:昵称   headImg:头像   password:密码
                    title: '',

                    nickname: '',

                    password: {
                        old: '',
                        pass: '',
                        rept: ''
                    },

                    // 头像数据
                    headImgList: [],
                    uploadData: {
                        token: useStore().state.token,
                    },
                },
                // login
                login: {
                    state: true,
                    form: {
                        account: '',
                        password: '',
                    }
                },
                // register
                register: {
                    state: false,
                    form: {
                        account: '',
                        password: '',
                        passwords: '',
                    }
                },
                // wx
                wx: {
                    state: false,
                    url: '',

                    tag: '',
                    code: '',
                },
            }
        },
        // DOM未渲染前调用
        created() {
            this.init();
        },
        // 方法
        methods: {
            // init
            init() {
                let that = this,
                    //userInfo = localStorage.getItem(website.info),
                    engine = localStorage.getItem(website.engine);

                that.config = config || {};
                //that.userInfo = userInfo ? JSON.parse(userInfo) : null;
                that.engine = engine ? JSON.parse(engine) : null;
                that.initWebSocket();
            },
            // 页面切换
            pageHref(url) {
                //console.log(url);
                this.$store.commit('openSettingPanel', false);
                goUrl(url);
            },

            // 显示用户信息抽屉
            showUserDrawer(type, title) {
                let that = this;
                if (!type) {
                    that.$message.warning('缺少: type');
                }
                if (!title) {
                    that.$message.warning('缺少: title');
                }
                if (type == 'nickname') {
                    that.user.nickname = that.store.userInfo ? that.store.userInfo.nickname : '';
                }
                that.user.type = type;
                that.user.title = title;
                that.user.state = true;
            },
            // 隐藏用户信息抽屉
            closeUserDrawer() {
                let that = this;
                that.user.type = '';
                that.user.title = '';
                that.user.state = false;
            },

            // 显示注册框
            showRegisterModal() {
                this.register.state = true;
                this.login.state = false;
            },
            // 隐藏注册框
            hideRegisterModal() {
                this.register.state = false;
                this.register.form = {
                    account: '',
                    password: '',
                    passwords: '',
                };
            },

            // 显示微信登录框
            showWxLoginModal() {
                let that = this,
                    code = getRandomNum(10);
                that.login.state = false;
                that.register.state = false;
                getWxAppletsDoor({
                    code: code,
                }).then(res => {
                    that.wx.url = res.data;
                    that.wx.state = true;
                    that.wx.code = code;
                    that.startSocket();
                }).catch(err => {
                    that.$message.error(err.msg);
                });
            },
            // 隐藏微信登录框
            hideWxLoginModal() {
                this.wx.state = false;
                this.wx.code = '';
                this.wx.url = '';
            },
            // 返回密码登录
            gotoLoginModal() {
                this.endSocket();
                this.showLoginModal();
            },

            // 显示登录框
            showLoginModal() {
                this.login.state = true;
                this.register.state = false;
                this.wx.state = false;
            },
            // 隐藏登录框
            hideLoginModal() {
                this.login.state = false;
                this.login.form = {
                    account: '',
                    password: '',
                };
            },
            // 初始化登录输入框
            initLoginForm() {
                this.login.form.account = '';
                this.login.form.password = '';
            },

            // 登录
            loginOk() {
                let that = this,
                    data = that.login.form;
                if (!data.account) {
                    that.$message.warning('请输入账号');
                    return false;
                }
                if (!data.password) {
                    that.$message.warning('请输入密码');
                    return false;
                }

                that.$store.dispatch('login', data).then(rps => {
                    clearStorage();
                    let msg = rps.msg || website.msg.success,
                        token = rps.token;
                    that.$message.success(msg);

                    that.loginSuccess(token);

                    that.initLoginForm();
                    that.hideLoginModal();
                }).catch(err => {
                    that.$message.error(err.msg || website.msg.error);
                })
            },
            // 注册
            registerOk() {
                let that = this,
                    data = that.register.form;
                if (!data.account) {
                    that.$message.warning('请输入账号');
                    return false;
                }
                if (!data.password) {
                    that.$message.warning('请输入密码');
                    return false;
                }
                if (!data.passwords) {
                    that.$message.warning('请再次输入密码');
                    return false;
                }
                that.$store.dispatch('register', data).then(res => {
                    that.$message.success(res.msg || website.msg.success);
                    that.hideRegisterModal();
                    that.showLoginModal();
                }).catch(err => {
                    that.$message.error(err.msg || website.msg.success);
                })
            },
            // 退出
            loginOut() {
                let that = this;
                that.$confirm({
                    title: '确认操作',
                    content: "确认登出?",
                    onOk() {
                        that.$store.dispatch('out').then(rps => {
                            that.$message.success(rps.msg || website.msg.success);
                            that.showLoginModal();
                            // 插件通信
                            sendMsgToExtension('out', null, res => {
                                console.log('sendMsgToExtension', res);
                                // 退出成功
                                if (res.type == 'out_success') {
                                    that.$message.success(res.msg || website.msg.success);
                                }
                            });
                        }).catch(err => {
                            that.$message.success(err.msg || website.msg.success);
                            // 插件通信
                            sendMsgToExtension('out', null, res => {
                                console.log('sendMsgToExtension1', res);
                                // 退出成功
                                if (res.type == 'out_success') {
                                    that.$message.success(res.msg || website.msg.success);
                                }
                            });
                        });
                    },
                    onCancel() {
                        // console.log('Cancel');
                    },
                });

            },
            // 登录成功处理
            loginSuccess(token) {
                let that = this;
                // 插件通信
                sendMsgToExtension('login', token, res => {
                    console.log('sendMsgToExtension', res);
                    if (res.type == 'login_success') {
                        that.$message.success(res.msg || website.msg.success);
                    }
                });

                // 用户信息
                that.$store.dispatch('getInfo').then(res => {
                    // 插件通信
                    sendMsgToExtension('info', res.info);
                });

                // 导航页Key
                that.$store.dispatch('getKey').then(res => {
                    // 插件通信
                    sendMsgToExtension('key', res.key);
                }).catch(err => {
                    // that.$message.error(err.msg);
                    that.$store.dispatch('out');
                    that.$confirm({
                        icon: createVNode(ExclamationCircleOutlined),
                        title: '提醒',
                        content: err.msg,
                        okText: '是',
                        cancelText: '否',
                        onOk() {
                            goUrl(appUrl);
                        },
                        onCancel() {
                        },
                    });
                });
            },
            // 小方格插件:插件通信(废弃)
            extensionSend(type = 'test', data = {msg: 'i am test msg'}) {
                let that = this;
                if (isChrome()) {
                    try {
                        chrome.runtime.sendMessage(
                            localStorage.getItem(website.exId),
                            {type: type, data: data},
                            function (res) {
                                if (res) {
                                    // console.log(res);
                                    // 登录成功
                                    if (res.type == 'login_success') {
                                        that.$message.success(res.msg || website.msg.success);
                                    }
                                    // 退出成功
                                    else if (res.type == 'out_success') {
                                        that.$message.success(res.msg || website.msg.success);
                                    }
                                } else {
                                    console.log('小方格插件:通信失败,请检查插件是否安装和插件ID是否匹配');
                                }
                            });
                    } catch (e) {
                        console.log('小方格插件:chrome.runtime.sendMessage catch:', e);
                    }
                } else {
                    console.log('小方格插件:只支持谷歌内核浏览器');
                }
            },
            // WebSocket 连接
            initWebSocket() {
                createSocket({url: wsUrl});
            },
            startSocket() {
                let code = this.wx.code;
                if (code) {
                    // 发送消息,设置page_key
                    sendWSPush({type: 'start_key', info: {id: code}});
                    // 监听事件
                    window.addEventListener('onmessageWS', this.getSocketData);
                }
            },
            endSocket() {
                let code = this.wx.code;
                if (code) {
                    // 发送消息,移除page_key
                    sendWSPush({type: 'end_key', info: {id: code}});
                    // 结束心跳
                    endPing();
                }
            },
            getSocketData(e) {
                let that = this;
                const data = e && e.detail.data;
                const object = JSON.parse(data);
                const type = object.type;
                const to = (object.info && object.info.id) ? object.info.id : '';
                // 连接成功
                if (type == 'start_key') {
                    that.wx.tag = '微信扫一扫';
                    if (to) {
                        // 发送心跳
                        sendPing(20000, JSON.stringify({type: 'ping', to: to}));
                    }
                }
                // 断开连接
                else if (type == 'end_key') {
                    that.wx.tag = '';
                }
                // 进入小程序
                else if (type == 'applets_success') {
                    that.wx.tag = '登录中';
                }
                // 登录成功
                else if (type == 'login_success') {
                    that.wx.tag = '登录成功';
                    that.$message.success(that.wx.tag);
                    let token = object.token;
                    that.$store.commit('setToken', token);
                    that.loginSuccess(token);
                    that.hideWxLoginModal();
                    // 在需要的时候卸载监听事件，比如离开页面
                    window.removeEventListener('onmessageWS', this.getSocketData);
                    closeSocket();
                }
                // 其它
                else {
                    console.log('other type:', type);
                }
            },
            // 修改昵称
            nicknameSubmit() {
                let that = this,
                    nickname = that.user.nickname;

                // console.log('nicknameSubmit', nickname);
                updateName({
                    name: nickname
                }).then(res => {
                    that.$message.success(res.msg);
                    that.user.nickname = '';
                    that.$store.dispatch("getInfo");
                    that.closeUserDrawer();
                }).catch(err => {
                    console.log(err);
                    that.$message.error(res.msg);
                })
            },
            // 修改密码
            passwordSubmit() {
                // console.log('passwordSubmit');
                let that = this,
                    password = that.user.password;
                console.log('passwordSubmit', password);
                updatePassword(password).then(res => {
                    that.$message.success(res.msg);
                }).catch(err => {
                    console.log(err);
                    that.$message.error(err.msg);
                })
            },
            // 头像url
            getHeadImgUrl() {
                return headImgUrl;
            },
            // 检测
            beforeUpload(file) {
                let that = this;
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    that.$message.error('上传的图片必须是Jpg或者Png格式!');
                    return false;
                }
                const isSize = file.size / 1024 / 1024 < 1;
                if (!isSize) {
                    that.$message.error('图片大小不能超过1MB!');
                    return false;
                }
                return true;
            },
            // 变更
            handleChange(info) {
                console.log('handleChange', info);
                let that = this;

                if (info.file.status !== 'uploading') {
                    console.log(info.file, info.fileList);
                }

                if (info.file.status === 'done') {
                    that.$message.success(`${info.file.name} 上传完成`);
                    that.$store.dispatch("getInfo");
                } else if (info.file.status === 'error') {
                    that.$message.error(`${info.file.name} 上传失败`);
                }
            },
            // 设置缓存
            setSetting(config) {
                localStorage.setItem(website.setting, JSON.stringify(config));
            },

            // 设置-打开搜索
            searchChange(e) {
                let that = this,
                    config = that.config,
                    value = e.target.value || 'new';
                config.openType.search.value = value;
                that.setSetting(config);
            },
            // 设置-打开图标
            quickChange(e) {
                let that = this,
                    config = that.config,
                    value = e.target.value || 'new';
                config.openType.quick.value = value;
                that.setSetting(config);
            },
            // 设置-打开书签
            bookmarkChange(e) {
                let that = this,
                    config = that.config,
                    value = e.target.value || 'new';
                config.openType.bookmark.value = value;
                that.setSetting(config);
            },
            // 清理缓存
            clearLocalStorage() {
                localStorage.clear();
                location.reload();
            },
        },
        // 监听
        watch: {
            // 登录失效后登录框显示
            '$store.state.token'(val) {
                if (val == '') {
                    this.showLoginModal();
                    this.closeUserDrawer();
                }
            },
        }
    }
</script>

<style lang="less" scoped>
    .user-info-wrap {
        /*padding-bottom: 8px;*/
        position: relative;

        .user-info-img {
            width: 50px;
            height: 50px;
            border-radius: 4px;
            overflow: hidden;
            float: left;
            margin-right: 10px;
            object-fit: cover;
            background-color: #f5f5f5;
        }

        .user-info-name {
            height: 30px;
            line-height: 30px;
            font-size: 16px;
        }

        .user-info-tel {
            height: 20px;
            line-height: 20px;
            font-size: 14px;
        }

        .user-info-setting {
            position: absolute;
            top: 10px;
            right: 10px;
        }

        div {
            font-size: 12px;
            color: #666666;
        }
    }

    .setting-list {
        padding: 8px 0;

        .setting-item {
            padding: 8px;
            user-select: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
            transition: background-color .2s ease-in-out;
            border-radius: 4px;

            &:hover {
                background: #efefef;
            }

            span {
                font-size: 14px;
                line-height: 1.3;
                color: #666666;
            }

            img {
                display: inline-block;
                width: 18px;
                height: 18px;
            }
        }
    }

    .app-card {
        margin-bottom: 15px;
    }

    .wx-wrap {
        text-align: center;

        .wx-img {
            display: inline-block;
            width: 152px;
            height: 152px;
        }
    }

    .head-img {
        min-width: 100px;
        max-width: 200px;
        border-radius: 4px;
    }

    .quick-key-card {
        .quick-key-value {
            background-color: #ececec;
            padding: 3px 8px;
            border-radius: 4px;
        }
    }
</style>
<style>
    .ant-form-vertical .ant-form-item:last-child {
        margin-bottom: 0;
    }
</style>
